package com.government.web.controller.system;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutionException;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.government.common.annotation.RepeatSubmit;
import com.government.common.enums.SmTemplateCode;
import com.government.common.exception.ServiceException;
import com.government.common.utils.ServletUtils;
import com.government.framework.web.service.TokenService;
import com.government.framework.web.service.VerifyCodeService;
import com.government.member.domain.MemberInfo;
import com.government.member.domain.Vip;
import com.government.member.mapper.MemberInfoMapper;
import com.government.member.mapper.VipMapper;
import com.government.member.service.BrowsingHistoryService;
import com.government.member.service.IMemberInfoService;
import com.government.member.service.UserHobbyService;
import com.government.member.service.VipOrderService;
import com.government.system.domain.ImMail;
import com.government.system.domain.bo.SendCodeBo;
import com.government.system.domain.vo.WebAuthVo;
import com.government.system.mapper.ImMailMapper;
import com.government.system.mapper.SysUserMapper;
import com.government.system.service.WebRoleAuthService;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.government.common.constant.Constants;
import com.government.common.core.domain.AjaxResult;
import com.government.common.core.domain.entity.SysMenu;
import com.government.common.core.domain.entity.SysUser;
import com.government.common.core.domain.model.LoginBody;
import com.government.common.utils.SecurityUtils;
import com.government.framework.web.service.SysLoginService;
import com.government.framework.web.service.SysPermissionService;
import com.government.system.service.ISysMenuService;

import static com.government.common.utils.SecurityUtils.getLoginUser;

/**
 * 登录验证
 *
 * @author system
 */
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private VipMapper vipMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private VipOrderService vipOrderService;
    @Autowired
    private UserHobbyService userHobbyService;
    @Autowired
    private BrowsingHistoryService browsingHistoryService;
    @Autowired
    private ImMailMapper messageMapper;
    @Autowired
    private VerifyCodeService verifyCodeService;
    @Autowired
    private MemberInfoMapper memberInfoMapper;
    @Autowired
    private WebRoleAuthService webRoleAuthService;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     * @response com.government.common.core.domain.AjaxResult<com.government.common.core.domain.entity.SysUser>
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);

        SysUser vipUserInfo = webRoleAuthService.getVipInfo(getLoginUser());
        user.setVip(vipUserInfo.getVip());
        user.setVipType(vipUserInfo.getVipType());
        user.setVipExpirationTime(vipUserInfo.getVipExpirationTime());

        int messageCount = messageMapper.selectCount(Wrappers.<ImMail>lambdaQuery().eq(ImMail::getUserId, user.getUserId()).eq(ImMail::getIsRead, "0"));
        user.setUnReadMessage(messageCount);
        user.setOrderNum(vipOrderService.selectOrderCountByUserId(user.getUserId()));
        user.setCollectNum(userHobbyService.selectCollectCountByUserId(user.getUserId()));
        user.setBrowsingNum(browsingHistoryService.selectBrowsingCountByUserId(user.getUserId()));

        MemberInfo memberInfo = memberInfoMapper.selectById(user.getUserId());
        String areaName = "";
        List<String> parkAreaIds = Lists.newArrayList();

        if (Objects.nonNull(memberInfo)) {
            areaName = memberInfo.getLastParkName();
            if (Objects.nonNull(memberInfo)) {
                if (StrUtil.isNotBlank(memberInfo.getParkAreaId())) {
                    String[] parkAreaIdStr = memberInfo.getParkAreaId().split(",");
                    parkAreaIds = Arrays.asList(parkAreaIdStr);
                }
                if (!SysUser.isAdmin(user.getUserId())) {
                    WebAuthVo webAuthVo = webRoleAuthService.getAuthContent();
                    int updMonth = Integer.parseInt(webAuthVo.getUaTime());
                    if (Objects.nonNull(memberInfo.getUpdAreaTime())) {
                        if (!webAuthVo.isUpdateArea()) {
                            user.setNextBindAreaTime(DateUtil.formatDate(DateUtil.offsetMonth(memberInfo.getUpdAreaTime(), updMonth)));
                        }
                    }
                }else{
                    user.setNextBindAreaTime("");
                }
            }
        }

        AjaxResult ajax = AjaxResult.success();
        user.setParkAreaIds(parkAreaIds);
        user.setAreaName(areaName);
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    @RepeatSubmit
    @RequestMapping(value = "/sendMsgCode", method = RequestMethod.POST)
    public AjaxResult sendMsgCode(@RequestBody SendCodeBo sendCodeBo) throws ExecutionException, InterruptedException {
        SmTemplateCode smTemplate = SmTemplateCode.canSend(sendCodeBo.getTemplateCode());
        ServiceException.throwExOnCondition(Objects.isNull(smTemplate), "验证码模板代码不正确");
        String code = verifyCodeService.sendCode(sendCodeBo.getPhone(), smTemplate);
        return AjaxResult.success();
    }
}
